import os
import subprocess
import time
from pages.excel_data_extraction import Excel_data_extraction
from config.settings import get_config
from base.base_page import BasePage


"""
封装功能函数

"""
class New_Access_Ip_Whitelist(BasePage):
    def __init__(self, driver, device_type, logger=None):
        super().__init__(driver, device_type, logger=logger)  # 传递日志实例
        self.driver = driver
        self.config = get_config(device_type)  # 获取全局配置
        self.excel_processor = Excel_data_extraction(self.driver, device_type, logger=logger)

    def create_access_ip_whitelist(self, interface_name, access_ip, ip_expiration_date, begin_end_time):
        # 进入IP白名单配置
        self.enter_new_access_ip_whitelist()
        # 停止已有配置状态
        self.update_access_ip_whitelist_status(interface_name, access_ip_status='停止')
        # 删除IP白名单
        self.delete_access_ip_whitelist(interface_name)
        # 点击新建IP白名单
        self.newly_access_ip_whitelist()
        # 输入接口名称
        self.input_data_interface(interface_name)
        # 输入IP地址
        self.input_access_ip(access_ip)
        # 输入IP地址有效期
        self.input_effective_time(ip_expiration_date, begin_end_time)
        # 保存IP白名单策略
        self.save_access_ip_whitelist(interface_name)

    def enter_new_access_ip_whitelist(self):
        # 进入新建访问数据接口IP白名单配置
        status = self.find_element('first_level_menu_module', 'interface_security_configure_status')
        if "ivu-menu-opened" in status.get_attribute("class"):
            pass
        else:
            self.click('first_level_menu_module', 'interface_security_configure')
        status = self.find_element('second_level_menu_module', 'ext_service_access_security_status')
        if "ivu-menu-opened" in status.get_attribute("class"):
            if self.quick_check_element('new_access_ip_whitelist', 'data_interface_name'):
                pass
            else:
                self.click('second_level_menu_module', 'ext_service_access_security')
        else:
            self.click('second_level_menu_module', 'ext_service_access_security')
            self.click('third_fourth_level_menu_module', 'new_access_ip_whitelist')
            self.soft_assert_element_visible('new_access_ip_whitelist', 'data_interface_name')

    def newly_access_ip_whitelist(self):
        self.enter_new_access_ip_whitelist()
        # 点击新建按钮
        self.click('common_elements', 'newly_built')
        self.soft_assert_element_visible('new_access_ip_whitelist', 'input_data_interface')

    def input_data_interface(self, interface_name):
        """ 输入数据接口 """
        selected_result = self.select_interface_options(
            element_locator='input_data_interface',
            values=interface_name,
            param_name='interface_name'
        )
        return selected_result

    def input_access_ip(self, access_ip):
        # 输入访问IP地址
        self.input_text('new_access_ip_whitelist', 'input_access_ip', access_ip)
        self.soft_assert_input_value('new_access_ip_whitelist', 'input_access_ip', access_ip)

    def input_effective_time(self, ip_expiration_date, begin_end_time):
        # 输入IP地址有效期
        if ip_expiration_date == '' or ip_expiration_date == '长期有效':
            pass
        else:
            self.click('new_access_ip_whitelist', 'effective_time')
            self.input_text('new_access_ip_whitelist', 'effective_time_begin_end', begin_end_time)
            self.soft_assert_input_value('new_access_ip_whitelist', 'effective_time_begin_end', begin_end_time)

    def save_access_ip_whitelist(self, interface_name):
        self.click('new_access_ip_whitelist', 'save_access_ip_whitelist')
        if self.quick_check_element('common_elements', 'add_success'):
            self.select_access_ip_whitelist_name(interface_name)
            self.logger.info(f'IP白名单配置：{interface_name} 保存成功')

    def update_access_ip_whitelist_status(self, interface_name, access_ip_status):
        """ 修改状态 """
        self.enter_new_access_ip_whitelist()
        if self.quick_check_element('common_elements', 'no_data'):
            pass
        else:
            result =  self.query_paged_data(
                search_locator='access_ip_whitelist_name',
                target_locator='access_ip_whitelist_status_all',
                value=interface_name,
                param_name='interface_name'
            )
            if result is None:
                pass
            else:
                if "ivu-switch-checked" in result.get_attribute("class"):
                    if access_ip_status == '启动':
                        pass
                    else:
                        result.click()
                        self.find_element('common_elements', 'status_update_success')
                        self.logger.info(f"时间、次数配置 '{interface_name}'停止成功")
                else:
                    if access_ip_status == '停止':
                        pass
                    else:
                        result.click()
                        self.find_element('common_elements', 'status_update_success')
                        self.logger.info(f"时间、次数配置 '{interface_name}'启动成功")

    def delete_access_ip_whitelist(self, interface_name):
        """
        支持分页查找并删除对象
        :param interface_name: 要删除的对象名称
        """
        if self.quick_check_element('common_elements', 'no_data'):
            pass
        else:
            current_page = 1
            while True:
                # 获取当前页所有对象名称
                name_elements = self.find_elements('new_access_ip_whitelist', 'access_ip_whitelist_name')
                # 遍历当前页
                for row_index, element in enumerate(name_elements, 1):
                    if element.text.strip() == interface_name:
                        self._delete_current_row(row_index)
                        if self.quick_check_element('common_elements', 'delete_success'):
                            self.logger.info(f"成功删除第{current_page}页的'{interface_name}'")
                        else:
                            self.logger.info(f"未成功删除第{current_page}页的'{interface_name}'")
                        return
                # 尝试翻页
                if not self._go_to_next_page():
                    break
                current_page += 1  # 等待分页加载

    def _delete_current_row(self, row_index):
        """执行单行删除操作"""
        delete_btn = self.find_dynamic_element(
            'new_access_ip_whitelist',
            'delete_access_ip_whitelist_all',
            row_index
        )
        # 点击删除按钮
        delete_btn.click()
        self.click('common_elements', 'confirm_button')
        self.find_element('common_elements', 'delete_success')

    def select_access_ip_whitelist_name(self, interface_name):
        """ 查看界面是否存在保存的接口名称 """
        selected_result = self.select_interface_options(
            element_locator='access_ip_whitelist_name',
            values=interface_name,
            param_name='interface_name'
        )
        return selected_result

    """##########################################  通用函数  ##########################################"""

    def query_paged_data(self, search_locator: str, target_locator: str, value: str, param_name: str):
        """通用分页数据查询方法（返回符合的元素、单值）"""
        # 标准化输入值
        target_text = str(value).strip()
        current_page = 1

        while True:
            # 获取当前页所有可选项
            options = self.find_elements('new_access_ip_whitelist', search_locator)

            # 遍历匹配选项
            for row_index, element in enumerate(options, 1):
                option_text = element.text.strip()
                if option_text == target_text:
                    # 获取同行的目标元素
                    target_element = self.find_dynamic_element(
                        'new_access_ip_whitelist',
                        target_locator,
                        row_index
                    )
                    return target_element  # 直接返回元素
                    # return target_element.text.strip() #直接返回字符串

            # 尝试翻页
            if not self._go_to_next_page():
                self.logger.debug(f"未找到匹配项: {target_text}，已遍历 {current_page} 页")
                return None  # 静默返回None

            current_page += 1

    def select_interface_options(self, element_locator: str, values: list, param_name: str):
        """通用接口选项选择方法（基础方法）"""
        # 类型统一处理
        if not isinstance(values, list):
            values = [values]

        selected = []
        for value in values:
            # 获取所有可选项
            options = self.find_elements('new_access_ip_whitelist', element_locator)

            # 标准化输入值
            target_text = str(value).strip()

            # 遍历匹配选项
            found = False
            for option in options:
                option_text = option.text.strip()
                if option_text == target_text:
                    self.highlight_element(option)  # 可视化点击元素
                    option.click()
                    selected.append(option_text)
                    found = True
                    break

            if not found:
                available_options = [opt.text.strip() for opt in options]
                raise ValueError(
                    f"参数 {param_name} 未找到选项: '{target_text}'\n"
                    f"可用选项: {available_options}"
                )
            return selected

    """##########################################  筛选  ##########################################"""

    def select_interface_name(self, interface_name):
        """筛选数据接口名称"""
        self.enter_new_access_ip_whitelist()
        self.click('new_access_ip_whitelist', 'select_interface_name')
        selected_result = self.select_interface_options(
            element_locator='select_interface_name_all',
            values=interface_name,
            param_name='interface_name'
        )
        self.soft_assert_input_value('new_access_ip_whitelist', 'select_interface_name', interface_name)
        return selected_result

    def get_access_ip(self, interface_name):
        """ 获取接口方向 """
        self.enter_new_access_ip_whitelist()
        result =  self.query_paged_data(
            search_locator='access_ip_whitelist_name',
            target_locator='access_ip_all',
            value=interface_name,
            param_name='interface_name'
        ).text.strip()
        self.logger.info(f"找到接口 '{interface_name}' 的访问IP：{result}")
        return result

    """##########################################  导出功能  ##########################################"""

    def export(self):
        # 导出
        self.click('common_elements', 'export')
        excel_file = self.excel_processor.wait_for_new_excel(timeout=60)
        return excel_file

    def export_access_ip_whitelist(self, interface_name, access_ip, ip_effective_time, create_time):
        excel_file = self.export()
        # 定义解析参数
        parse_params = {
            "sheet_name": "1-100",
            "start_row": 3,
            "headers": ["序号", "数据接口名称", "访问IP地址", "IP有效期(天)", "创建时间", "启/停"],
            "max_rows": 10
        }

        # 解析Excel内容
        excel_data = self.excel_processor.parse_excel(excel_file, parse_params)

        # 只处理第一个数据条目
        for item in excel_data:
            # 记录完整数据
            self.logger.info("正在验证导出的令牌数据：")
            for key, value in item.items():
                self.logger.info(f"{key}: {value}")

            # 数据预处理
            excel_values = {
                '数据接口名称': str(item.get('数据接口名称', '')).strip(),
                '访问IP地址': str(item.get('访问IP地址', '')).strip(),
                'IP有效期(天)': str(item.get('IP有效期(天)', '')).strip(),
                '创建时间': str(item.get('创建时间', '')).strip()
            }

            # 字段比较验证
            comparisons = [
                ('数据接口名称', excel_values['数据接口名称'], interface_name),
                ('访问IP地址', excel_values['访问IP地址'], access_ip),
                ('IP有效期(天)', excel_values['IP有效期(天)'], ip_effective_time),
                ('创建时间', excel_values['创建时间'], create_time)
            ]

            # 执行所有字段比较
            all_match = True
            for field, actual, expected in comparisons:
                # 统一None处理
                actual = actual if actual != 'None' else None
                expected = str(expected).strip() if expected is not None else None
                if actual == expected:
                    self.logger.info(f"{field}匹配成功: {actual}")
                else:
                    all_match = False
                    self.logger.error(f"{field}匹配失败 | Excel值: {actual} | 期望值: {expected}")
            # 输出最终结果
            if all_match:
                self.logger.info("所有字段验证通过")
            else:
                self.logger.error("存在字段验证失败")
            # 无论是否匹配，执行一次后退出循环
            break

    def access_ip_whitelist_data(self, *fields):
        field_map = {
            "interface_name": "first_interface_name",
            "access_ip": "first_access_ip",
            "ip_effective_time": "first_ip_effective_time",
            "create_time": "first_create_time",
            "up_down": "first_up_down"
        }
        # 如果没有传参，默认返回全部字段（保持原顺序）
        if not fields:
            fields = ("interface_name", "access_ip", "ip_effective_time", "create_time", "up_down")
        # 根据映射关系获取值
        result = []
        for field in fields:
            mapped_field = field_map.get(field)
            if not mapped_field:  # 处理无效参数名
                raise ValueError(f"无效参数名: {field}")
            result.append(self.get_element_text("new_access_ip_whitelist", mapped_field))
        # 如果只传单个参数，直接返回标量值（可选）
        return tuple(result) if len(result) > 1 else result[0] if result else None

    def safe_operate_window(self, class_name: str, max_retries: int = 5) -> bool:
        """安全的窗口操作流程（针对深度系统优化）"""
        for attempt in range(max_retries):
            try:
                # 动态获取窗口 ID（仅选择可见窗口）
                win_id = subprocess.check_output(
                    ["xdotool", "search", "--onlyvisible", "--class", class_name],
                    timeout=5
                ).decode().strip().split('\n')[0]

                if not win_id:
                    print(f"Attempt {attempt + 1}: Window not found, retrying...")
                    continue
                # 验证窗口有效性
                subprocess.check_call(["xdotool", "getwindowgeometry", win_id], timeout=3)
                # 安全激活窗口（深度系统专用顺序）
                subprocess.run(["xdotool", "windowactivate", "--sync", win_id], check=True)
                subprocess.run(["xdotool", "windowraise", win_id], check=True)
                return True
            except (subprocess.CalledProcessError, IndexError, subprocess.TimeoutExpired) as e:
                time.sleep(1.5)

        print("Failed to operate window after all retries")
        return False

    def paste_path(self, target_path: str):
        """通过剪贴板粘贴路径（深度系统专用）"""
        # 转换为绝对路径
        abs_path = os.path.abspath(os.path.expanduser(target_path))
        try:
            # 复制到剪贴板
            subprocess.run(
                ["xclip", "-selection", "clipboard"],
                input=abs_path.encode("utf-8"),
                check=True
            )
            # 发送粘贴快捷键
            subprocess.run(["xdotool", "key", "ctrl+v"], check=True)
            time.sleep(1)
            # 停止全部xclip进程，不停止会导致残留进程，无其他办法解决
            subprocess.run(
                ["pkill", "-f", "xclip"],
                capture_output=True,
                text=True)
        except subprocess.CalledProcessError as e:
            print(f"操作失败: {str(e)}")

    def import_access_ip_whitelist(self, target_path):
        # 点击导入按钮（根据实际页面元素调整定位方式）
        if self.find_element('common_elements', 'import'):
            self.click('common_elements', 'import')
            # 等待文件选择框弹出
            time.sleep(1)
            self.safe_operate_window(class_name='dde-select-dialog-x11')
            # 跳转到下载目录（假设需要选择下载文件夹中的最新文件）
            subprocess.run(["xdotool", "key", "ctrl+l"])  # 聚焦地址栏
            self.paste_path(target_path)
            subprocess.run(["xdotool", "key", "Return"])  # 回车确认
            time.sleep(1)
            for i in range(1, 6):
                subprocess.run(["xdotool", "key", "Return"]) # 回车进入目录内
            # 选择最新文件（排序后第一个文件）
            subprocess.run(["xdotool", "key", "Down"])  # 确保焦点在第一个文件
            time.sleep(1)
            subprocess.run(["xdotool", "key", "Return"])  # 回车确认
            if self.quick_check_element('common_elements', 'import_success'):
                self.logger.info("文件导入成功")
            else:
                self.logger.error("文件导入失败")
